package com.chatplus.application.processor.listener;

import cn.hutool.json.JSONObject;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.common.util.MessageTokenUtil;
import com.chatplus.application.processor.StreamEventSourceListener;
import com.chatplus.application.processor.constant.AIConstants;
import com.unfbx.chatgpt.utils.TikTokensUtil;
import okhttp3.sse.EventSource;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.socket.WebSocketSession;

import java.util.Objects;

/**
 * 文心一言监听器
 *
 * @author chj
 * @date 2024/1/4
 **/
public class BaiduEventSourceListener extends StreamEventSourceListener {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(BaiduEventSourceListener.class);
    String reply = "";


    public BaiduEventSourceListener(WebSocketSession session, String platform, String prompt) {
        super(session, platform, prompt);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onEvent(@NotNull EventSource eventSource, String id, String type, @NotNull String data) {
        LOGGER.message("baidu返回数据").context("data", data).info();
        JSONObject jsonObject = new JSONObject(data);
        String result = jsonObject.getStr("result");
        if (Objects.nonNull(result)) {
            chatAiUtilHandler.sendMessage(result);
            reply += result;
        }
        if (Boolean.TRUE.equals(jsonObject.getBool("is_end"))) {
            LOGGER.message("回答完成").info();
            chatAiUtilHandler.saveChatHistory(reply);
            chatAiUtilHandler.sendMessage(AIConstants.END_LABEL);
        }
    }
}